
//
//  AppDelegate+LocalNotification.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/9/9.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "AppDelegate+LocalNotification.h"
#import "WZScheduleRemindController.h"
#import "JKAlertDialog.h"
#import <UserNotifications/UserNotifications.h>
#import "NetWorkShare.h"
#import "NSDate+convenience.h"
#import "WZScheduleList.h"
#import "LocationNotification.h"
#import "OAloginViewController.h"

#define LocalNotification_Active_Remind_Title   @"提示"
#define LocalNotification_Active_Remind_Message @"确定跳转到日程提醒页面"
#define LocalNotification_Active_Remind_OKBtn   @"好的"
#define LocalNotification_Active_Remind_Cancel  @"取消"
#define LocalNotification_Userinfo_KEY          @"scheduleTitle"
#define LocalNotification_detail @"localNotification_detail"

#define LocalNotification_ScheduleTitle_KEY @"scheduleTitle"
#define LocalNotification_ScheduleID_KEY @"scheduleID"
#define LocalNotification_ScheduleStartTime_KEY @"scheduleStartTime"
#define LocalNotification_ScheduleStartDate_KEY @"scheduleStartDate"

#define IOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

//NSString *const WZScheduRemindOfLocalNoticfication = @"WZScheduRemindOfLocalNoticfication";

@implementation AppDelegate (LocalNotification)

#pragma mark - 接收到通知时回调

- (void)application:(UIApplication *)application HandleBackCallWithNotification:(UILocalNotification *)localNotification {
    
    
    WZScheduleRemindController *scheduleVc = [[WZScheduleRemindController alloc] init];
    scheduleVc.ln = localNotification;
    NSString *lnName = localNotification.userInfo[LocalNotification_Userinfo_KEY];
    WZLog(@"lnName = %@",lnName);
//        NSDictionary *dict = @{LocalNotification_Userinfo_KEY:lnName};
//        [[NSNotificationCenter defaultCenter] postNotificationName:WZScheduRemindOfLocalNoticfication object:nil userInfo:dict];
    
    if (application.applicationState == UIApplicationStateActive) {
        
        [self.window.rootViewController presentViewController:scheduleVc animated:YES completion:^{
            
            
        }];
        
    } else if (application.applicationState == UIApplicationStateInactive) {
        
        [self.window.rootViewController presentViewController:scheduleVc animated:YES completion:^{
            
            // 弹出之后回调
            WZLog(@"modal 出了提醒控制器");
            
        }];
        
    } else if (application.applicationState == UIApplicationStateBackground) {
        
        // 程序在后台运行
//        [self.window.rootViewController presentViewController:scheduleVc animated:YES completion:^{
//            
//        }];
    }
}


#pragma mark - 应用程序被杀死, 接收到本地通知时

- (void)application:(UIApplication *)application launchFinishedWithOptions:(NSDictionary *) launchOptions LocalNotification:(UILocalNotification *)localNotification {
    
    /*
    // 注册通知
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 10.0) {
        
        // 使用 UNUserNotificationCenter 来管理通知
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        //监听回调事件
        center.delegate = self;
        
        //iOS 10 使用以下方法注册，才能得到授权
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                              completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                  // Enable or disable features based on authorization.
                              }];
        
        //获取当前的通知设置，UNNotificationSettings 是只读对象，不能直接修改，只能通过以下方法获取
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            
        }];
        
    } else {
        
        
    }
    
    */
    
    UILocalNotification *ln = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
    
    if (ln) {
        
        WZScheduleRemindController *scheduleVc = [[WZScheduleRemindController alloc] init];
        scheduleVc.ln = localNotification;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:WZScheduRemindOfLocalNoticfication object:nil userInfo:nil];
        
        [self.window.rootViewController presentViewController:scheduleVc animated:YES completion:^{
            
        }];
    }
}



#pragma mark - 创建通知

- (void)application:(UIApplication *)application RegistLocalNotificationOfeverySchedule:(NSDate *)startDate {
    
    NSString *oaUserID = [USER_DEFAULT objectForKey:@"oaUserId"];
    if (oaUserID) {
        NSCalendar *greCalendar = [NSCalendar currentCalendar];
        // 开始日期
        NSDate *beginDate = [NSDate dateWithTimeIntervalSinceNow:16 * 60];
        NSString *beginTime = [NSString stringWithFormat:@"%ld", [NSDate cTimestampFromDate:beginDate] * 1000];
        
        // 判断本月有几天
        NSRange range = [greCalendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:beginDate];
        
        NSDate *endDate = [beginDate dateByAddingTimeInterval:range.length * 24 * 3600 - 1];
        NSString *endTime = [NSString stringWithFormat:@"%ld", [NSDate cTimestampFromDate:endDate] * 1000];
        
        NSString *oaUserName = [[USER_DEFAULT objectForKey:@"oaUserName"] stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
        NSString *oaPwd = [[USER_DEFAULT objectForKey:@"oaPwd"] md5String];
        [NetWorkShare queryScheduleWithUserName:oaUserName pwd:oaPwd beginTime:beginTime endTime:endTime alertBeginTime:nil alertEndTime:nil successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                NSArray *scheduleArray = [WZScheduleList objectArrayWithKeyValuesArray:responseObject[@"rows"]];
                
                for (WZScheduleList *schedule in scheduleArray) {
                    
                    // 如果是日程并没有注册通知
                    if (schedule.typeFlag == 2) {
                        
                        // 获取线程中的提醒
                        NSArray *lns = [UIApplication sharedApplication].scheduledLocalNotifications;
                        for (UILocalNotification *ln in lns) {
                            NSString *scheduleTitle = ln.userInfo[LocalNotification_ScheduleTitle_KEY];
                            NSString *alertTime = ln.userInfo[LocalNotification_ScheduleStartTime_KEY];
                            NSString *scheduleID = ln.userInfo[LocalNotification_ScheduleID_KEY];
                            if (![schedule.title isEqualToString:scheduleTitle] && ![schedule.scheduleID isEqualToString:scheduleID]) {
                                // 提醒时间
                                NSString *alertTime = [NSString stringWithFormat:@"%lld", (schedule.startTime - 15 * 3600)];
                                NSDate *fireDate = [NSDate dateFromString:alertTime format:@"yyyy-MM-dd HH:mm"];
                                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                                [dict setObject:schedule.title forKey:LocalNotification_ScheduleTitle_KEY];
                                [dict setObject:[NSString stringWithFormat:@"%lld", schedule.startDate] forKey:LocalNotification_ScheduleStartDate_KEY];
                                [dict setObject:[NSString stringWithFormat:@"%lld", schedule.startTime] forKey:LocalNotification_ScheduleStartTime_KEY];
                                [dict setObject:schedule.scheduleID forKey:LocalNotification_ScheduleID_KEY];
                                
                                [LocationNotification registerLocalNotificationWithFireDate:fireDate repeatType:0 entity:dict];
                            }
                        }
                    }
                }
                
            } else {
                
            }
            
        } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
    }
}



- (void)testNotification {
    
    UILocalNotification *localNoti =
    [UILocalNotification new];
    localNoti.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
    localNoti.alertBody = @"测试本地通知111";
    localNoti.alertTitle = @"本地通知111";
    localNoti.alertAction = @"打开111";
    localNoti.soundName = UILocalNotificationDefaultSoundName;
    localNoti.repeatInterval = NSCalendarUnitMinute;
    //    localNoti.repeatCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    localNoti.applicationIconBadgeNumber = 123;
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    userInfo[@"name"] = @"haha111";
    localNoti.userInfo = userInfo;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNoti];
    
    UILocalNotification *localNoti2 =
    [UILocalNotification new];
    localNoti2.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
    localNoti2.alertBody = @"测试本地通知222";
    localNoti2.alertTitle = @"本地通知222";
    localNoti2.alertAction = @"打开2222";
    localNoti2.soundName = UILocalNotificationDefaultSoundName;
    localNoti.repeatInterval = NSCalendarUnitMinute;
    localNoti.repeatCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierChinese];
    localNoti2.applicationIconBadgeNumber = 123;
    NSMutableDictionary *userInfo2 = [NSMutableDictionary dictionary];
    userInfo[@"name"] = @"haha222";
    localNoti2.userInfo = userInfo2;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNoti2];

}

@end
